#!/bin/bash
# Initially based on a snippet from the greenlet project.
# This needs to be run from the root of the project.
# To update: docker pull quay.io/pypa/manylinux2010_x86_64
set -e
export PYTHONUNBUFFERED=1
export PYTHONDONTWRITEBYTECODE=1
# Use a fixed hash seed for reproducibility
export PYTHONHASHSEED=8675309
export CI=1
export TRAVIS=true
# Don't get warnings about Python 2 support being deprecated. We
# know. The env var works for pip 20.
export PIP_NO_PYTHON_VERSION_WARNING=1
export PIP_NO_WARN_SCRIPT_LOCATION=1


if [ -d /greenlet -a -d /opt/python ]; then
    # Running inside docker
    export GREENLET_MANYLINUX=1
    # Build for speed (we're going to test this anyway) and without assertions.
    # Note: -Ofast includes -ffast-math which affects process-wide floating-point flags (e.g. can affect numpy).
    # It may also violate standards compliance in a few ways. Rather than opt-out with -fno-fast-math,
    # we use O3, which has neither of those problems.
    export CFLAGS="-O3 -DNDEBUG"
    # Build in an isolated directory
    mkdir /tmp/build
    cd /tmp/build
    git clone /greenlet greenlet
    cd greenlet

    mkdir -p /greenlet/wheelhouse
    OPATH="$PATH"
    which auditwheel
    for variant in `ls -d /opt/python/cp{37,38,39,310,311,312}*`; do
        export PATH="$variant/bin:$OPATH"
        echo "Building $variant $(python --version)"

        python -mpip install -U pip
        python -mpip install -U setuptools wheel
        python -mpip wheel --wheel-dir ./dist .
        python -mpip install -U .[test]
        python -m unittest discover -v greenlet.tests
        PATH="$OPATH" auditwheel repair dist/greenlet*.whl
        cp wheelhouse/greenlet*.whl /greenlet/wheelhouse

        rm -rf build
        rm -f dist/greenlet*.whl

    done

    exit 0
fi

# Mount the current directory as /greenlet
# Can't use -i on Travis with arm64, "input device not a tty"
docker run --rm -v "$(pwd):/greenlet"  ${DOCKER_IMAGE:-quay.io/pypa/manylinux2014_x86_64} /greenlet/$(basename $0)
ls -l wheelhouse
